package org.easy.tool.service.impl;

import org.easy.tool.common.*;
import org.easy.tool.entity.FileRecord;
import org.easy.tool.entity.Problem;
import org.easy.tool.mapper.FileRecordMapper;
import org.easy.tool.mapper.ProblemMapper;
import org.easy.tool.service.IFileRecord;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 文件服务
 *
 * @author Valley
 * @since 2024-09-08 13:27:04
 */
@Service
public class FileRecordService extends ServiceImpl<FileRecordMapper, FileRecord> implements IFileRecord {


    @Autowired
    ProblemMapper problemMapper;

    @Value("${westudy.file.temp-dir}") private String tempDir;
    @Value("${westudy.file.url}") private String fileUrl;
    @Value("${westudy.file.img-dir}") private String imgDir;


    @Override
    public String upload(MultipartFile file) throws Exception {
        //记录上传
        FileRecord record = new FileRecord();
        String randomID = RandomUtil.randomID();
        record.setId(randomID);
        String fileName = file.getOriginalFilename();
        record.setFileName(fileName);
        record.setUserId("admin");
        String[] split = fileName.split("\\.");
        record.setFileType(split[1]);
        record.setActionType("upload");
        record.setCreateTime(TimeUtil.nowMS());
        record.setUpdateTime(TimeUtil.nowMS());
        save(record);
        //上传文件
        String fileDir = imgDir + File.separator + randomID;
        if (!new File(fileDir).exists()) {
            new File(fileDir).mkdirs();
        }
        String savePath = fileDir + File.separator + fileName;
        file.transferTo(new File(savePath));
        return randomID;
    }

    @Override
    public void preview(String id) throws Exception {
        String fileName = getById(id).getFileName();
        String filePath = imgDir + File.separator + id + File.separator + fileName;
        HttpUtil.preview(WebUtil.req(), WebUtil.res(), filePath);
    }

    private void exportProblemExplainWord(String docTitle, List<Problem> problemList, boolean withProblem, boolean withExplain){
        try {
            String temp = tempDir + RandomUtil.randomID() + ".docx";
            List<String> contentList = new ArrayList<>();
            for (int i = 0; i < problemList.size(); i++) {
                Problem problem = problemList.get(i);
                String problemTitle = "第" + (i + 1) + "题:" + problem.getTitle();
                contentList.add(problemTitle);
                if (withProblem){
                    String contentImg = problem.getTitleImg();
                    String contentUrl = fileUrl + contentImg;
                    contentList.add(contentUrl);
                }
                if (withExplain) {
                    String answerImg = problem.getExplainImg();
                    String answerUrl = fileUrl + answerImg;
                    contentList.add(answerUrl);
                }
            }
            boolean status = WordUtil.write07(temp, docTitle, contentList, tempDir);
            HttpUtil.downloadFile(WebUtil.req(), WebUtil.res(), new File(temp));
            FileIOUtil.delete(temp);
            LogUtil.info("导出成功:{}", status);
        }catch (Exception e){
            LogUtil.info("导出失败:{}", e.getMessage());
        }

    }

    private void exportProblemExplainWord(LinkedHashMap data, boolean withProblem, boolean withExplain) {
        Object titleObj = data.get("docTitle");
        String docTitle = "";
        if (StringUtil.isBlank(titleObj)){
            docTitle = TimeUtil.todayYMDToCN();
        }else {
            docTitle = (String) titleObj;
        }
        List<LinkedHashMap> list = (List<LinkedHashMap>) data.get("problemList");
        List<Problem> problemList = list.stream().map(item -> {
            String id = (String) item.get("id");
            return problemMapper.selectById(id);
        }).collect(Collectors.toList());
        exportProblemExplainWord(docTitle, problemList, withProblem, withExplain);
    }

    @Override
    public void exportProblemWord(LinkedHashMap data) {
        exportProblemExplainWord(data, true, false);
    }

    @Override
    public void exportProblemExplainWord(LinkedHashMap data) {
        exportProblemExplainWord(data, true, true);
    }

    @Override
    public void picturePreview(String id) throws Exception {
        String filePath = imgDir + File.separator + id;
        HttpUtil.preview(WebUtil.req(), WebUtil.res(), filePath);
    }

    @Override
    public void exportExplainWord(LinkedHashMap data) {
        exportProblemExplainWord(data, false, true);
    }
}
